import unittest
from chernc.utils.md_utils import extract_code_blocks_with_language
from chernc.analyzer.semanticpiece import extractPiecesFromSlice 
import os

class FakeSlice:
    def __init__(self,t):
        self.text = t

class TestSemanticPiecesRead(unittest.TestCase):
    pass


#return a lambda, bu do not add a 
def generate_method_from_md_file(md_string):
    code_blocks = extract_code_blocks_with_language(md_string)
    cpp_block = ""
    for l,c in code_blocks:
        if l == "cpp":
            cpp_block=c
            break
    if cpp_block == "":
        raise Exception(f"the md file does not have a cpp code block!\n:{md_string}")
    s = FakeSlice(cpp_block)
    def closure(self):
        #get the cpp block
        self.assertIsInstance(extractPiecesFromSlice(s), list)
    return closure

def dynamically_add_methods_from_md_directory(k, directory):
    # first, read all md files from the directory
    md_files =  [f for f in os.listdir(directory) if f.endswith('.md')]
    # then, generate a method from the file
    for md in md_files:
        with open(os.path.abspath(os.path.join(directory, md)) , 'r', encoding='utf-8') as f:
            content = f.read()
            method = generate_method_from_md_file(content)
            setattr(k,"_".join(["test",md]),method)
dynamically_add_methods_from_md_directory(TestSemanticPiecesRead,os.path.abspath(os.path.join(os.path.dirname(__file__), 'c_rust_cases')))


if __name__ == '__main__':
    unittest.main()